<template>
  <div :id="'window-'+uniqueid" :class="showWindow ? 'fadeInDown': 'fadeOutUp'" class="am-drag-wrap animated">
    <div :id="'window-header-'+uniqueid" class="drag-header">
      <div class="drag-wrap">
        <div class="drag-title" />
        <div class="drag-options">
          <span class=" icon svg-container" @click="fullScreen">
            <svg-icon icon-class="full-screen" />
          </span>
          <span class="icon svg-container" @click="closeWindow">
            <svg-icon icon-class="close" />
          </span>
        </div>
      </div>
    </div>
    <div class="drag-content">
      <div class="tabs-header-wrap">
        <div
          v-for="(item,index) in tabs"
          ref="tag"
          :key="item.component"
          class="tabs-header-title"
          :class="index === tabIndex ? 'tables-active' : ''"
          @contextmenu="openMenu(index,$event)"
        >
          <span v-if="index === tabIndex " class="point hover" />
          <span class="title" @click="changeTabIndex(index,$event)">{{ item.title }}</span>
          <span class="icon svg-container" @click="closeTabs(index,$event)">
            <svg-icon icon-class="close" />
          </span>
        </div>
      </div>
      <div class="tabs-content-warp">
        <div
          v-for="(item,index) in tabs"
          :key="item.component"
          class="contentWrap"
          :class="index === tabIndex ? 'tables-content-active' : ''"
        >
          <component :is="item.component" type="primary" />
        </div>
      </div>
    </div>

    <div class="tabContextWrap" :class="`tabContextWrap${uniqueid}`">
      <div v-show="contextMenuVisible" class="conetextUl contextmenu">
        <div @click="refreshSelectedMenuIndex(selectedMenuIndex)">刷新</div>
        <div @click="closeSelectedMenuIndex(selectedMenuIndex)">关闭</div>
        <div @click="closeOthersTags(selectedMenuIndex)">关闭其他</div>
        <div @click="closeAllTags(selectedMenuIndex)">关闭所有</div>
      </div>
    </div>

    <div :id="`drag-right-size-${uniqueid}`" class="drag-right-size" />
    <div :id="`drag-bottom-size-${uniqueid}`" class="drag-bottom-size" />
    <div :id="`drag-bottom-right-size-${uniqueid}`" class="drag-bottom-right-size" />
  </div>
</template>

<script>
let _this = null
export default {
  name: 'Window',
  data() {
    return {
      isFullscreen: false,
      uniqueid: 'uniqueid',
      closeDialogVisible: false,
      showWindow: false,
      windowMinWidth: 400,
      windowMinHeight: 300,
      contextMenuVisible: false,
      selectedMenuIndex: 0
    }
  },

  computed: {
    tabs() {
      return this.$store.state.window.tabs
    },
    tabIndex() {
      return this.$store.state.window.index
    }
  },
  watch: {
    'tabs': function(newFlag, oldFlag) {
      if (newFlag.length > 0) {
        if (_this) {
          this.showWindow = true
          this.initWindowStyle()
        }
      }
    }
    // 需要执行的代码
  },
  mounted() {
    _this = this
    this.init()
    // 左右监听拖拽
    this.leftRightResize()
    // 上下拖拽
    this.topBottomResize()
    // 改变窗口大小监听
    this.resizeWindow()
  },

  methods: {
    initWindowStyle() {
      if (!this.isInitWindowStyle) {
        const sty = this.sty()
        const dragDom = document.getElementById('window-' + this.uniqueid)
        const width = sty(dragDom, 'width').replace('px', '')
        const height = sty(dragDom, 'height').replace('px', '')
        const left = (document.body.clientWidth - width) / 2
        const top = (document.body.clientHeight - height) / 2
        dragDom.style.left = left + 'px'
        dragDom.style.top = top + 'px'
        this.isInitWindowStyle = true
      }
    },

    leftRightResize() {
      const sty = this.sty()
      const dragDom = document.getElementById('window-' + this.uniqueid)
      const drayElement = document.getElementById('drag-right-size-' + this.uniqueid)
      drayElement.onmousedown = (e) => {
        const originX = e.clientX
        // eslint-disable-next-line no-unused-vars
        let styW = sty(dragDom, 'width')
        styW = +styW.replace('px', '')
        document.onmousemove = (e) => {
          this.closeTransition()
          let width = parseInt(styW) + (e.clientX - originX)
          if (width < this.windowMinWidth) {
            width = this.windowMinWidth
          }
          dragDom.style.cssText += `;width:${width}px;`
        }
        this.closeDocumentMove()
        return false
      }
    },
    topBottomResize() {
      const sty = this.sty()
      const dragDom = document.getElementById('window-' + this.uniqueid)
      const drayElement = document.getElementById('drag-bottom-size-' + this.uniqueid)
      drayElement.onmousedown = (e) => {
        this.closeTransition()
        const originY = e.clientY
        let styH = sty(dragDom, 'height')
        styH = +styH.replace('px', '')
        document.onmousemove = (e) => {
          let height = parseInt(styH) + (e.clientY - originY)
          if (height < this.windowMinHeight) {
            height = this.windowHeight
          }
          dragDom.style.cssText += `;height:${height}px;`
        }
        this.closeDocumentMove()
        return false
      }
    },

    resizeWindow() {
      const sty = this.sty()
      const dragDom = document.getElementById('window-' + this.uniqueid)
      const drayElement = document.getElementById('drag-bottom-right-size-' + this.uniqueid)
      drayElement.onmousedown = (e) => {
        this.closeTransition()
        const originY = e.clientY
        const orignX = e.clientX
        // eslint-disable-next-line no-unused-vars
        let styH = sty(dragDom, 'height')
        let styW = sty(dragDom, 'width')
        styH = +styH.replace('px', '')
        styW = +styW.replace('px', '')
        document.onmousemove = (e) => {
          let height = parseInt(styH) + (e.clientY - originY)
          let width = parseInt(styW) + (e.clientX - orignX)
          if (height < this.windowMinHeight) {
            height = this.windowHeight
          }
          if (width < this.windowMinWidth) {
            width = this.windowMinWidth
          }
          dragDom.style.cssText += `;height:${height}px;width:${width}px`
        }
        this.closeDocumentMove()
        return false
      }
    },

    openMenu(index, e) {
      const sty = this.sty()
      this.selectedMenuIndex = index
      const dragDom = document.getElementById('window-' + this.uniqueid)
      let wrapLeft = sty(dragDom, 'left')
      let wrapTop = sty(dragDom, 'top')
      wrapTop = wrapTop.replace('px', '')
      wrapLeft = wrapLeft.replace('px', '')
      const left = e.clientX - wrapLeft - 10
      const top = e.clientY - wrapTop - 10

      const oWrap = document.getElementsByClassName(`tabContextWrap${this.uniqueid}`)[0]
      oWrap.style.cssText += `;top:${top}px;left:${left}px`
      e.preventDefault()
      this.contextMenuVisible = true
      document.onclick = () => {
        this.contextMenuVisible = false
        document.onclick = null
      }
      return false
    },

    init() {
      const sty = this.sty()
      const dragDom = document.getElementById('window-' + this.uniqueid)
      const dialogHeaderEl = document.getElementById('window-header-' + this.uniqueid)
      dialogHeaderEl.onmousedown = (e) => {
        // 鼠标按下，计算当前元素距离可视区的距离
        const disX = e.clientX - dialogHeaderEl.offsetLeft
        const disY = e.clientY - dialogHeaderEl.offsetTop

        const screenWidth = document.body.clientWidth // body当前宽度
        const screenHeight = document.documentElement.clientHeight // 可见区域高度(应为body高度，可某些环境下无法获取)

        const dragDomWidth = dragDom.offsetWidth // 对话框宽度
        const dragDomheight = dragDom.offsetHeight // 对话框高度

        const minDragDomLeft = dragDom.offsetLeft
        const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth

        const minDragDomTop = dragDom.offsetTop
        const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight

        // 获取到的值带px 正则匹配替换
        let styL = sty(dragDom, 'left')
        let styT = sty(dragDom, 'top')

        // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
        if (styL.includes('%')) {
          styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100)
          styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100)
        } else {
          styL = +styL.replace('px', '')
          styT = +styT.replace('px', '')
        }

        document.onmousemove = function(e) {
          // 通过事件委托，计算移动的距离
          let left = e.clientX - disX
          let top = e.clientY - disY + 18

          // 边界处理
          if (-(left) > minDragDomLeft) {
            left = -(minDragDomLeft)
          } else if (left > maxDragDomLeft) {
            left = maxDragDomLeft
          }

          if (-(top) > minDragDomTop) {
            top = -(minDragDomTop)
          } else if (top > maxDragDomTop) {
            top = maxDragDomTop
          }

          // 移动当前元素
          dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`
        }
        this.closeDocumentMove()
        return false
      }
    },

    closeDocumentMove() {
      document.onmouseup = function(e) {
        document.onmousemove = null
        document.onmouseup = null
      }
    },

    sty() {
      if (window.document.currentStyle) {
        return (dom, attr) => dom.currentStyle[attr]
      } else {
        return (dom, attr) => getComputedStyle(dom, false)[attr]
      }
    },
    closeWindow(e) {
      if (this.tabs.length > 1) {
        this.$bus.emit('conformDialog', {
          title: '关闭所有标签',
          content: '当前有多个标签页面正在打开，您确定关闭所有吗？',
          successFn: this.handleCloseWindow
        })
      } else {
        this.handleCloseWindow()
      }
    },

    handleCloseWindow() {
      this.showWindow = false
      setTimeout(() => {
        this.$store.dispatch('window/deleteTabTabs')
      }, 400)
    },

    fullScreen() {
      const dom = document.getElementById('window-' + this.uniqueid)
      if (!this.isFullscreen) {
        this.windowLeft = this.sty()(dom, 'left')
        this.windowTop = this.sty()(dom, 'top')
        this.windowWidth = this.sty()(dom, 'width')
        this.windowHeight = this.sty()(dom, 'height')
        dom.style.transition = '0.4s'
        dom.style.left = 0
        dom.style.top = 0
        dom.style.width = document.body.clientWidth + 'px'
        dom.style.height = document.body.clientHeight + 'px'
      } else {
        dom.style.left = this.windowLeft
        dom.style.top = this.windowTop
        dom.style.width = this.windowWidth
        dom.style.height = this.windowHeight
        setTimeout(() => {
          this.closeTransition()
        }, 500)
      }
      this.isFullscreen = !this.isFullscreen
    },

    closeTransition() {
      if (this.isFullscreen) {
        const dom = document.getElementById('window-' + this.uniqueid)
        dom.style.transition = ''
        this.isFullscreen = false
      }
    },

    closeTabs(index, event) {
      if (this.tabs.length < 2) {
        this.handleCloseWindow()
      }
      this.$store.dispatch('window/deleteTabIndex', index)
    },

    changeTabIndex(index) {
      if (index !== this.tabIndex) {
        this.$store.dispatch('window/changeTabIndex', index)
      }
      return false
    },

    refreshSelectedMenuIndex(index) {

    },
    closeSelectedMenuIndex(index) {
      this.closeTabs(index)
    },
    closeOthersTags(index) {
      this.$store.dispatch('window/closeOther', index)
    },
    closeAllTags(index) {
      this.closeWindow()
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "~@/styles/variables.scss";

  $borderWrapWidth: 18px;
  .am-drag-wrap {
    width: 1000px;
    height: 600px;
    background: $windowBackgroundColor;
    position: absolute;
    top: -2000px;
    left: -1000px;
    box-shadow: 0 20px 68px rgba(0, 0, 0, .55);
    border: $borderWrapWidth solid transparent;
    border-image: url("../../../assets/borderimage/table_border.png") 20 26 20 26 round;
    z-index: 301;
    display: flex;
    flex-direction: column;
    animation-duration: 0.4s;

    .drag-header {
      width: 100%;
      height: 48px;
      position: absolute;
      top: -18px;
      cursor: move;

      .drag-wrap {
        height: 30px;
        margin-top: 18px;
        line-height: 30px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        font-size: 14px;
        background: rgba(15, 47, 48, 0.6) !important;
        border-bottom: 1px solid $nodeBorderColor;

      }

      .icon {
        width: 18px;
        height: 18px;
        margin-right: 2px;
        cursor: default;
        color: $fontWhiteColor;
        padding: 2px;

        &:hover {
          cursor: pointer;
          background: $windowHoverColor;
        }
      }
    }

    .drag-content {
      flex: 1;
      margin-top: 30px;
      /*background-color: rgba(15, 47, 48, 0.1);*/
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

  }

  .drag-right-size {
    position: absolute;
    width: $borderWrapWidth;
    height: 100%;
    right: -$borderWrapWidth;
    top: 0;
    cursor: ew-resize;
  }

  .drag-bottom-size {
    position: absolute;
    width: 100%;
    height: $borderWrapWidth;
    bottom: -$borderWrapWidth;
    left: 0;
    cursor: ns-resize;
  }

  .drag-bottom-right-size {
    position: absolute;
    width: $borderWrapWidth;
    height: $borderWrapWidth;
    right: -$borderWrapWidth;
    bottom: -$borderWrapWidth;
    cursor: nwse-resize;
  }

  .tabContextWrap{
    position: absolute;
    top: -9000px;
    left: -9000px;
    z-index: 10000;
    background-color: $nodeBk;
    box-shadow: 0 2px 5px rgba(0, 0, 0, .55);
    .contextmenu{
      margin:0;
      div{
        padding-left: 10px;
        padding-right: 20px;
        border-bottom: 1px solid $nodeBorderColor;
        line-height: 30px;
        height: 30px;
        font-size: 14px;
        color: $fontWhiteColor;
        cursor: pointer;
        &:hover{
          background-color: $hoverColor;
        }
      }

    }
  }

  $tabHeaderHeight: 24px;

  .tabs-header-wrap {
    margin: 4px 0;
    display: flex;
    flex-direction: row;

    .tables-active {
      background-color: $tabActiveColor;
    }

    .tabs-header-title {
      margin-left: 5px;
      font-size: 14px;
      height: $tabHeaderHeight;
      padding: 0 10px;
      border-top-left-radius: 30px;
      border-bottom-right-radius: 30px;
      border: 1px solid $nodeBorderColor;
      display: flex;
      flex-direction: row;
      align-content: center;
      align-items: center;
      overflow: hidden;

      .point {
        width: 10px;
        height: 10px;
        border-radius: 5px;
        background-color: $fontWhiteColor;
        line-height: $tabHeaderHeight;
        display: inline-block;
      }

      .title {
        cursor: pointer;
        margin-left: 5px;
        display: inline-block;
        line-height: $tabHeaderHeight;
      }

      .svg-container {
        line-height: $tabHeaderHeight;
        display: inline-block;
        width: 20px;
        text-align: center;
        cursor: pointer;
        position: relative;
        top: 1px;

        &:hover {
          background-color: $hoverColor;
        }
      }
    }

    color: #fff;
  }

  .tabs-content-warp {
    border-top: 1px solid #6398a1;
    margin-top: 5px;
    flex: 1;
    display: flex;
    overflow: hidden;

    .contentWrap {
      flex: 1;
      display: none;
      overflow-y: scroll;
    }

    .tables-content-active {
      display: block;
    }
  }

  .test--ss {
    position: absolute;
  }
</style>
